package com.jhd.fuzhou.view.punishment;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.jhd.fuzhou.view.login.BaseActivity;
import com.jhd.fuzhou.view.login.FuzhouApplication;
import com.jhd.fuzhou.R;
import com.jhd.fuzhou.service.PunishmentService;
import com.jhd.fuzhou.util.AdministrativeProcess;
import com.jhd.fuzhou.util.CustomToast;
import com.jhd.fuzhou.util.DialogSize;
import com.jhd.fuzhou.util.UtilHelper;
import com.jhd.fuzhou.vo.AdministrativePunishmentVo;
import com.jhd.fuzhou.vo.JsonForResult;
import com.jhd.fuzhou.vo.PersonInfoVo;
import com.jhd.fuzhou.vo.SysUserVo;

import net.zigin.commons.util.ParamsMapUtil;
import net.zigin.commons.util.StringUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class AuditAdministrativeActivity extends BaseActivity {
    @BindView(R.id.rel_next_audit)RelativeLayout rel_next_audit;
    @BindView(R.id.tv_next_audit)TextView tv_next_audit;
    @BindView(R.id.lin_suggestion)LinearLayout lin_suggestion;
    @BindView(R.id.linearLayout)LinearLayout linearLayout;
    @BindView(R.id.et_suggestion)EditText et_suggestion;
    private String data;
    private String message;//审核意见
    private String pass="1";
    private Context context=this;
    private List<PersonInfoVo> personInfoVos;
    private AdministrativePunishmentVo administrativePunishmentVo;
    private List<SysUserVo> sysUserVoList;
    private AlertDialog _alertDialog;
    private String username;

    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.activity_audit_administrative);
    }

    @Override
    protected void processLogic() {
        onBack();
        application.addPunishmentActivity(this);
        data=getIntent().getStringExtra("data");
        administrativePunishmentVo= JSON.parseObject(data, AdministrativePunishmentVo.class);
        getSysUserListAll();
        if(administrativePunishmentVo.getProgress().equals("案件受理")){
            linearLayout.setVisibility(View.GONE);
        }
    }
    @OnClick({R.id.rel_next_audit,R.id.rb_status_1,R.id.rb_status_2,R.id.btn_cancel,R.id.btn_post})
    public void onClick(View v){
        switch (v.getId()){
            case R.id.rel_next_audit:
                dialogShow(tv_next_audit);
                break;
            case R.id.btn_post:
                if(administrativePunishmentVo.getProgress().equals("案件受理")){
                    if("请选择".equals(tv_next_audit.getText().toString())){
                        CustomToast.showText(context,"请选择下级审批人",3000,0,0).show();
                    }else{
                        AdministrativeProcess.completeByAssign(application,administrativePunishmentVo.getTaskId(),username,administrativePunishmentVo.getProgress(),null,context);
                    }
                    //AdministrativeProcess.getProInstanceId(application,administrativePunishmentVo.getId(),administrativePunishmentVo.getProgress(),null,username,context);
                }else{
                    if(pass.equals("2")){
                        if(StringUtil.isNullOrEmpty(et_suggestion.getText().toString().trim())){
                            CustomToast.showText(context,"请输入审核意见!",3000,0,0).show();
                        }else{
                            AdministrativeProcess.backNodes(application,administrativePunishmentVo.getTaskId(),administrativePunishmentVo.getProgress(),et_suggestion.getText().toString(),context);
                        }
                        //AdministrativeProcess.getProInstanceId(application,administrativePunishmentVo.getId(),administrativePunishmentVo.getProgress(),et_suggestion.getText().toString(),null,context);
                    }else{
                        if("请选择".equals(tv_next_audit.getText().toString())){
                            CustomToast.showText(context,"请选择下级审批人!",3000,0,0).show();
                        }else{
                            AdministrativeProcess.completeByAssign(application,administrativePunishmentVo.getTaskId(),username,administrativePunishmentVo.getProgress(),null,context);
                            //AdministrativeProcess.getProInstanceId(application,administrativePunishmentVo.getId(),administrativePunishmentVo.getProgress(),null,username,context);
                        }
                    }
                }
                break;
            case R.id.btn_cancel:
                onCancel();
                break;
            case R.id.rb_status_1:
                lin_suggestion.setVisibility(View.GONE);rel_next_audit.setVisibility(View.VISIBLE);
                pass="1";
                break;
            case R.id.rb_status_2:
                lin_suggestion.setVisibility(View.VISIBLE);rel_next_audit.setVisibility(View.GONE);
                pass="2";
                break;
        }
    }
    public void onCancel() {
        Intent intent = new Intent();
        intent.putExtra("position","2");
        ((Activity)context).setResult(RESULT_OK, intent);
        ((Activity)context).finish();
    }
    /*获取审批人列表*/
    public void getSysUserListAll(){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        PunishmentService vs = retrofit.create(PunishmentService.class);
        Map<String, String> params = ParamsMapUtil.getInstance("userId",application.getUserId());
        Call<JsonForResult> jsonForResultCall = vs.getSysUserListAll(application.getAccessToken(),params);//调用接口获取json返回
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        if(jsonForResult.getData()!=null){
                            sysUserVoList= JSON.parseArray(jsonForResult.getData().toString(), SysUserVo.class);
                        }else{
                            sysUserVoList=new ArrayList<>();
                        }
                    } else {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                } catch (Exception e) {
                    CustomToast.showText(context,e.getLocalizedMessage(),3000,0,0).show();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "网络异常!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }
    public void dialogShow(TextView textView){
        LayoutInflater mLayoutInflater = LayoutInflater.from(this);
        View view = mLayoutInflater.inflate(R.layout.dialog_person_choose, null);
        final AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context, R.style.ActionSheetDialogStyle);
        alertBuilder.setView(view);
        _alertDialog = alertBuilder.create();
        //获取当前Activity所在的窗体
        Window window = _alertDialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        DialogSize.setDialogSize(view,context);
        _alertDialog.show();
        ImageView iv_dismiss = (ImageView) view.findViewById(R.id.iv_dismiss);
        TextView tv_title = (TextView) view.findViewById(R.id.tv_title);
        LinearLayout lin_parent = (LinearLayout) view.findViewById(R.id.lin_parent);
//        lin_parent.
        RecyclerView rv_choose = (RecyclerView) view.findViewById(R.id.rv_choose);
        LinearLayoutManager layoutManage = new LinearLayoutManager(context);
        rv_choose.setLayoutManager(layoutManage);
        tv_title.setText("监督员");//标题要改一下
        EditText et_search = (EditText) view.findViewById(R.id.et_search);
        ImageView iv_cancel = (ImageView) view.findViewById(R.id.iv_cancel);
        List<SysUserVo> sysUserVoList2=new ArrayList<>();//用来展示的list
        SupervisorAdapter recyclerAdapter=new SupervisorAdapter(sysUserVoList);
        rv_choose.setAdapter(recyclerAdapter);
        et_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                sysUserVoList2.clear();
                if(!s.toString().equals("")){
                    iv_cancel.setVisibility(View.VISIBLE);
                }else{
                    iv_cancel.setVisibility(View.GONE);
                }
                for (SysUserVo sysUserVo : sysUserVoList) {
                    if(sysUserVo.getName().contains(s.toString())){
                        sysUserVoList2.add(sysUserVo);
                    }
                }
                SupervisorAdapter recyclerAdapter=new SupervisorAdapter(sysUserVoList2);
                rv_choose.setAdapter(recyclerAdapter);
            }
        });
        iv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                et_search.setText("");iv_cancel.setVisibility(View.GONE);
                SupervisorAdapter recyclerAdapter=new SupervisorAdapter(sysUserVoList);
                rv_choose.setAdapter(recyclerAdapter);
            }
        });
        iv_dismiss.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                _alertDialog.dismiss();
            }
        });
        WindowManager.LayoutParams params = window.getAttributes() ;
        params.width =(int) (getWindowManager().getDefaultDisplay().getWidth());//使用这种方式更改了dialog的框宽
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(params);
    }

    public class SupervisorAdapter extends RecyclerView.Adapter<SupervisorAdapter.ViewHolder> {
        private int checkPosition=-1;
        List<SysUserVo> sysUserVos;

        public SupervisorAdapter( List<SysUserVo> sysUserVos) {
            this.sysUserVos=sysUserVos;
        }

        @Override
        public SupervisorAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_question_choose, parent, false);
            SupervisorAdapter.ViewHolder viewHolder = new SupervisorAdapter.ViewHolder(itemView);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull SupervisorAdapter.ViewHolder holder, int position) {
            holder.tv_choose.setText(sysUserVos.get(position).getName());
            if(sysUserVos.get(position).getName().equals(tv_next_audit.getText().toString())){
                holder.image.setVisibility(View.VISIBLE);
            }

            holder.relativeLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    tv_next_audit.setText(sysUserVos.get(position).getName());
                    username=sysUserVos.get(position).getUserName();
                    _alertDialog.dismiss();
                    checkPosition=position;
                    notifyDataSetChanged();
                }
            });
            if(position==checkPosition){
                holder.image.setVisibility(View.VISIBLE);
            }else{
                holder.image.setVisibility(View.GONE);
            }
        }

        @Override
        public int getItemCount() {
            return sysUserVos.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            TextView tv_choose;ImageView image;
            RelativeLayout relativeLayout;
            public ViewHolder(View itemView) {
                super(itemView);
                this.tv_choose = itemView.findViewById(R.id.tv_choose);
                this.image = itemView.findViewById(R.id.image);
                this.relativeLayout = itemView.findViewById(R.id.relativeLayout);
            }
        }
    }
}